// 测试 /chat/add 前端接入与会话ID逻辑
import { chatSession } from '../utils/index.js';
import { chatAdd } from '../api/roleApi.js';

const log = (...args) => console.log('[testChatAdd]', ...args);
const err = (...args) => console.error('[testChatAdd]', ...args);

// 用例1：验证 chatId 生成逻辑
export const testGenerateChatId = () => {
  const roleId = 9999;
  chatSession.reset(roleId);
  const id1 = chatSession.ensure(roleId);
  const id2 = chatSession.ensure(roleId);
  log('生成的chatId:', id1);
  if (!id1 || typeof id1 !== 'string') err('chatId 非字符串或空');
  if (id1 !== id2) err('同一角色chatId未保持一致');
  const roleId2 = 10000;
  chatSession.reset(roleId2);
  const id3 = chatSession.ensure(roleId2);
  log('不同角色chatId:', id3);
  if (id1 === id3) err('不同角色生成的chatId重复');
};

// 用例2：测试会话ID保持功能
export const testSessionConsistency = () => {
  const roleId = 42;
  chatSession.reset(roleId);
  const idA = chatSession.ensure(roleId);
  const idB = chatSession.ensure(roleId);
  if (idA !== idB) err('会话ID不一致');
  chatSession.reset(roleId);
  const idC = chatSession.ensure(roleId);
  if (idC === idA) err('重置后chatId未变化');
  log('会话一致性验证通过:', { beforeReset: idA, afterReset: idC });
};

// 用例3：检查参数校验有效性
export const testParamValidation = async () => {
  const roleName = '测试角色';
  const roleId = 12345;
  const chatId = chatSession.ensure(roleId);
  try {
    await chatAdd({ role: roleName, prompt: '', chatId });
    err('空prompt未触发校验错误');
  } catch (e) {
    log('空prompt触发校验错误，正常');
  }
  try {
    await chatAdd({ role: roleName, prompt: 'hello', chatId: '' });
    err('空chatId未触发校验错误');
  } catch (e) {
    log('空chatId触发校验错误，正常');
  }
};

// 用例4：验证异常处理流程完整性（需后端不可达或返回错误状态）
export const testExceptionFlow = async () => {
  try {
    const roleId = 777;
    const chatId = chatSession.ensure(roleId);
    // 若后端未实现 /api/chat/add 或不可达，调用将抛出异常
    await chatAdd({ role: '异常验证', prompt: '触发异常', chatId });
    log('若未报错，说明后端返回了成功（请手动验证返回内容）');
  } catch (e) {
    log('捕获到接口异常，异常处理流程正常:', e?.message);
  }
};

// 直接运行脚本时执行所有用例
if (import.meta.url === new URL(process.argv[1], import.meta.url).href) {
  (async () => {
    testGenerateChatId();
    testSessionConsistency();
    await testParamValidation();
    await testExceptionFlow();
  })();
}